package basic

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"project/controller"
	"project/mySql"
	"time"
)

/**
 * @File : feed.go
 * @Description : 视频流相关方法
 * @Author : 吴概
 * @Date : 2023/2/1
 */

// FeedResponse 视频流的Response
type FeedResponse struct {
	controller.Response
	VideosList []controller.Video `json:"video_list,omitempty"`
	NextTime   int64              `json:"next_time,omitempty"`
}

// Feed 视频流
func Feed(c *gin.Context) {
	videosList := mySql.GetVideosList()
	like := mySql.GetLike(mySql.GetUserByToken(c.Query("token")).Id)
	likeIdlist := controller.GetIdList(like.LikeList)
	if len(likeIdlist) != 0 {
		for _, v := range likeIdlist {
			videosList[v-1].IsFavorite = true
			fmt.Println(videosList[v-1].Id)
		}
	}
	sortVideosList(&videosList, 0, len(controller.DemoVideos))
	c.JSON(http.StatusOK, FeedResponse{
		Response:   controller.Response{StatusCode: 0},
		VideosList: videosList,
		NextTime:   time.Now().Unix(),
	})
}

// 使用快速排序对视频列表排序排序（按视频上传时间倒序排序）
func sortVideosList(list *[]controller.Video, left, right int) {
	if left >= right {
		return
	}
	tempList := *list
	pivot, _ := time.Parse("2006-01-02 15:04:05", tempList[left].Time)
	j := left
	for i := left; i < right; i++ {
		temp, _ := time.Parse("2006-01-02 15:04:05", tempList[i].Time)
		if temp.After(pivot) {
			j++
			tempList[j], tempList[i] = tempList[i], tempList[j]
		}
	}
	tempList[left], tempList[j] = tempList[j], tempList[left]
	sortVideosList(list, left, j)
	sortVideosList(list, j+1, j)
}
